var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server = app.listen(3000);
var io = require('socket.io').listen(server);
var path = require('path');


app.use('/static', express.static(path.join(__dirname, './static')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
})
app.post('/login', (req, res) => {
    if (!checkUserName(req.body.username)) {
        // 设置cookie 30分钟过期
        res.cookie('username', req.body.username, { expires: new Date(Date.now() + 30 * 60 *1000) });
        res.send({success: true, message: "登录成功"});
    } else {
        res.send({success: false, message: "登录失败"});
    }
})
let users = [];
let usersNum = 0;
io.on('connection', (socket) => {
    socket.on('login', (data) => {
        if (!checkUserName(data.username)) {
            users.push({ username: data.username, message: [] });
            usersNum = users.length;
        };
        io.emit('loginResult', { code: 0, users, usersNum, loginUser: data.username });
        setTimeout(() => {
            users = users.filter((user) => user.username !== data.username);
            usersNum = users.length; 
            socket.disconnect(true)
        }, 30 * 60 *1000);
        console.log(`用户${data.username}登录成功，进入聊天室，当前在线登录人数：${usersNum}`);
    });
    socket.on('disconnect', (data) => {
        usersNum = users.length;
        console.log('Info:', data);
        console.log(`当前在线登录人数：${usersNum}`);
    });
    socket.on('sendMessage', (data) => {
        for (let _user of users) {
            if(_user.username === data.username) {
                _user.message.push(data.message);
                io.emit('receiveMessage', data);
                break;
            }
        }
    });
    socket.on('logout', (data) => {
            users = users.filter((user) => user.username !== data.username);
            usersNum = users.length;
            io.emit('logoutResult', { users, usersNum, logoutUser: data.username });
            console.log(`用户 ${data.username} 离开了聊天室!`)

    })
  
})


const checkUserName = (username) =>{
    let isExist = false;
    users.forEach((user) => {
        if (user.username === username) {
            isExist = true;
        }
    });
    return isExist;
}